<?php 

namespace controladores;

//require(JS_LIBS.'ckeditor/kcfinder/core/bootstrap.php');
use fcf\Controller as Controller,
	fcf\view as View;
use utils\Utils;


class Imagenes extends Controller{

	public function imagenPortadaNoticia(){
		if($_SERVER['REQUEST_METHOD'] == "POST") {
		
			$dst_x = 0;
			$dst_y = 0;
		
			$src_x = $_POST['x']; // crop Start x
			$src_y = $_POST['y']; // crop Srart y
		
			$src_w = $_POST['w']; // $src_x + $dst_w
			$src_h = $_POST['h']; // $src_y + $dst_h
		
			// resize image
			// currentlty the default width and height of image from aspect ratio
			//$dst_w = $_GET['w']; // image width
			//$dst_h = $_GET['h']; // image height
			//$dst_w = 320 - 80;
			//$dst_h = 320 - 80;
			$dst_w = 886;
			$dst_h = 293;
			// resize image variable
			$image = imagecreatetruecolor($dst_w,$dst_h);
		
			// create image
			$source = imagecreatefromjpeg($_POST['image']);
		
			// crop
			imagecopyresampled($image, $source, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
		
			// image name
			$name = sha1(uniqid(mt_rand(), true));
		
			// location to save cropped image
			$url = $_SERVER['DOCUMENT_ROOT']."/test/assets/img/noticies/".$name.'.jpg';
		
			// save image
			imagejpeg($image, $url, 100);
		
			// return URL
			$validation = array (
					'url' => $name.'.jpg'
			);
			echo json_encode($validation);
		}
	} 
	
	public function uploadCKimagen(){
		$uploader = "kcfinder\\uploader";  // To execute core/bootstrap.php on older
		$uploader = new $uploader();       // PHP versions (even PHP 4)
		$uploader->upload();
	}
	
	function uploadImatgeJocNetNoticies(){
		
		
		if(isset($_POST)){
			############ Edit settings ##############
			$ThumbSquareSize 		= 200; //Thumbnail will be 200x200
			$BigImageMaxSize 		= 665; //Image Maximum height or width
			$ThumbPrefix			= "thumb_"; //Normal thumb Prefix
			$DestinationDirectory = $_SERVER['DOCUMENT_ROOT'].'/jocnet/images/noticies/';
			$Quality 				= 100; //jpeg quality
			##########################################
			//check if this is an ajax request
			if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die(); 	}
				// Random number will be added after image name
				$RandomNumber 	= rand(0, 9999999999);
				$ImageName 		= str_replace(' ','-',strtolower($_FILES['file']['name'])); //get image name
				
				
				$ImageSize 		= $_FILES['file']['size']; // get original image size
				$TempSrc	 	= $_FILES['file']['tmp_name']; // Temp name of image file stored in PHP tmp folder
				$ImageType	 	= $_FILES['file']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
	
				list($w, $h, $type, $attr) = getimagesize($_FILES["file"]['tmp_name']);
				/*
				if($w != '665' || $h != '415'){ 
				    $info['error'] = true;
					$info['mensaje'] = 'La imagen ha de ser de 665x415px';
					return Response::json($info);
				}*/
			//Let's check allowed $ImageType, we use PHP SWITCH statement here
			switch(strtolower($ImageType)){
				case 'image/png':
					//Create a new image from file
					$CreatedImage =  imagecreatefrompng($_FILES['file']['tmp_name']);
					break;
				case 'image/gif':
					$CreatedImage =  imagecreatefromgif($_FILES['file']['tmp_name']);
					break;
				case 'image/jpeg':
				case 'image/pjpeg':
					$CreatedImage = imagecreatefromjpeg($_FILES['file']['tmp_name']);
					break;
				default:
					$info['error'] = true;
					$info['mensaje'] = 'Unsupported File!';
					return Response::json($info);
			}
		
			//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
			//Get first two values from image, width and height.
			//list assign svalues to $CurWidth,$CurHeight
			list($CurWidth,$CurHeight)=getimagesize($TempSrc);
		
			//Get file extension from Image name, this will be added after random name
			$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
			$ImageExt = str_replace('.','',$ImageExt);
		
			//remove extension from filename
			$ImageName 		= preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
			//Construct a new name with random number and extension.
			$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
			//set the Destination Image
			$thumb_DestRandImageName 	= $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
			$DestRandImageName 			= $DestinationDirectory.$NewImageName; // Image with destination directory
			//Resize image to Specified Size by calling resizeImage function.
			
				if($this->resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)){
					//Create a square Thumbnail right after, this time we are using cropImage() function
					if(!$this->cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)){
					//	echo 'Error Creating thumbnail';
					}
					$info[0]['thumbnail'] = $ThumbPrefix.$NewImageName;
					//$info[0]['image'] = $NewImageName;
					return Response::json($info[0]);
				}else{
					die('Resize Error'); //output error
				}
			}	 
		}
	
		
		// This function will proportionally resize image
		function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType){
			$this->layout = '';
			
			//Check Image size is not 0
			if($CurWidth <= 0 || $CurHeight <= 0){
				return false;
			}
		
			//Construct a proportional size of new image
			$ImageScale      	= min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
			$NewWidth  			= ceil($ImageScale*$CurWidth);
			$NewHeight 			= ceil($ImageScale*$CurHeight);
			$NewCanves 			= imagecreatetruecolor($NewWidth, $NewHeight);
			
			imagecolortransparent($NewCanves, imagecolorallocatealpha($NewCanves, 0, 0, 0, 127));
			imagealphablending($NewCanves, false);
			imagesavealpha($NewCanves, true);
			// Resize Image
			if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0,0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)){
				switch(strtolower($ImageType)){
					case 'image/png':
						imagepng($NewCanves,$DestFolder);
						break;
					case 'image/gif':
						imagegif($NewCanves,$DestFolder);
						break;
					case 'image/jpeg':
					case 'image/pjpeg':
						imagejpeg($NewCanves,$DestFolder,$Quality);
						break;
					default:
						return false;
				}
				//Destroy image, frees memory
				if(is_resource($NewCanves)) {
					imagedestroy($NewCanves);
				}
				return true;
			}
		
		}
		




		//This function corps image to create exact square images, no matter what its original size!
		function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType){
			$this->layout = '';
			//Check Image size is not 0
			if($CurWidth <= 0 || $CurHeight <= 0){
				return false;
			}
		
			//abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9
			if($CurWidth>$CurHeight){
				$y_offset = 0;
				$x_offset = ($CurWidth - $CurHeight) / 2;
				$square_size 	= $CurWidth - ($x_offset * 2);
			}else{
				$x_offset = 0;
				$y_offset = ($CurHeight - $CurWidth) / 2;
				$square_size = $CurHeight - ($y_offset * 2);
			}
		
			$NewCanves = imagecreatetruecolor($iSize, $iSize);
			if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)){
				switch(strtolower($ImageType)){
					case 'image/png':
						imagepng($NewCanves,$DestFolder);
						break;
					case 'image/gif':
						imagegif($NewCanves,$DestFolder);
						break;
					case 'image/jpeg':
					case 'image/pjpeg':
						imagejpeg($NewCanves,$DestFolder,$Quality);
						break;
					default:
						return false;
				}
				//Destroy image, frees memory
				if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
				return true;
		
			}
		
		}
		
		
		function imagenContenidoNoticia(){
			$uploader = "kcfinder\\uploader";  // To execute core/bootstrap.php on older
			$uploader = new $uploader();       // PHP versions (even PHP 4)
			$uploader->upload();
		}
		
		
		function guardarImagenNoticia(){
			$imagePath = RUTA_UPLOAD_CONTENIDO."img/noticies/";
			
			$allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG");
			$temp = explode(".", $_FILES["img"]["name"]);
			$extension = end($temp);
			
			if ( in_array($extension, $allowedExts)){
				
				if ($_FILES["img"]["error"] > 0){
					$response = array(
							"status" => 'error',
							"message" => 'ERROR Return Code: '. $_FILES["img"]["error"],
					);
					echo "Return Code: " . $_FILES["img"]["error"] . "<br>";
				
				}else{
						
					$filename = $_FILES["img"]["tmp_name"];
					list($width, $height) = getimagesize( $filename );
			
					move_uploaded_file($filename,  $imagePath . $_FILES["img"]["name"]);
			
					$response = array(
							"status" => 'success',
							"url" => RUTA_CONTENIDO_FCF."img/noticies/".$_FILES["img"]["name"],
							"width" => $width,
							"height" => $height
					);
			
				}
			}
			else
			{
				$response = array(
						"status" => 'error',
						"message" => 'something went wrong',
				);
			}
			 
			echo json_encode($response);
		}
		
		function cropImagenNoticia(){

			/*
			 *	!!! THIS IS JUST AN EXAMPLE !!!, PLEASE USE ImageMagick or some other quality image processing libraries
			*/
			
			$imgUrl = $_POST['imgUrl'];
			$imgInitW = $_POST['imgInitW'];
			$imgInitH = $_POST['imgInitH'];
			$imgW = $_POST['imgW'];
			$imgH = $_POST['imgH'];
			$imgY1 = $_POST['imgY1'];
			$imgX1 = $_POST['imgX1'];
			$cropW = $_POST['cropW'];
			$cropH = $_POST['cropH'];
			
			$jpeg_quality = 100;
			
			$archivo = Utils::randomString(17,false,true);
			$output_filename = RUTA_UPLOAD_CONTENIDO."img/noticies/".$archivo;
			
			$what = getimagesize($imgUrl);
			
			
			switch(strtolower($what['mime']))
			{
				case 'image/png':
					$img_r = imagecreatefrompng($imgUrl);
					$source_image = imagecreatefrompng($imgUrl);
					$type = '.png';
					break;
				case 'image/jpeg':
					$img_r = imagecreatefromjpeg($imgUrl);
					$source_image = imagecreatefromjpeg($imgUrl);
					$type = '.jpeg';
					break;
				case 'image/gif':
					$img_r = imagecreatefromgif($imgUrl);
					$source_image = imagecreatefromgif($imgUrl);
					$type = '.gif';
					break;
				default: die('image type not supported');
			}
			
			$resizedImage = imagecreatetruecolor($imgW, $imgH);
			imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW,
			$imgH, $imgInitW, $imgInitH);
			
			
			$dest_image = imagecreatetruecolor($cropW, $cropH);
			imagecopyresampled($dest_image, $resizedImage, 0, 0, $imgX1, $imgY1, $cropW,
			$cropH, $cropW, $cropH);
			
			imagejpeg($dest_image, $output_filename.$type, $jpeg_quality);
			$foto_borrar = explode("/",$imgUrl);
			$foto_borrar = end($foto_borrar);
			$response = array(
					"status" => 'success',
					"url" => RUTA_CONTENIDO_FCF.'img/noticies/'.$archivo.$type,
					"archivo" => $foto_borrar
			);
			//$borrar = str_replace(SERVER,"",$imgUrl);
			
			unlink(RUTA_UPLOAD_CONTENIDO."img/noticies/".$foto_borrar);
			echo json_encode($response);

		}
		
}

?>